import { _decorator, AudioClip, AudioSource, Component, director, Node, resources } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager {

    //设计成单例
    private static _instance: AudioManager;
    public static get Instance(): AudioManager {
        if (!this._instance) {
            this._instance = new AudioManager();
        }
        return this._instance;
    }
    //AudioSource组件用于控制音频播放
    private bgmSource: AudioSource | null = null; // 专用BGM通道;
    private effectSource: AudioSource | null = null; // 专用音效通道

    private _volume: number = 1.0;//默认音量（部分web平台（ios）限制并不会生效）
    private _sound_on: boolean = true;//音效开关

    constructor() {
        //创建一个空节点
        let audio_node = new Node();
        audio_node.name = '__audio_node__';
        //把创建的节点添加到场景中
        director.getScene().addChild(audio_node);
        //设置为常驻节点
        director.addPersistRootNode(audio_node);
        //添加AudioSource组件
        this.bgmSource = audio_node.addComponent(AudioSource)!;
        //添加AudioSource组件
        this.effectSource = audio_node.addComponent(AudioSource)!;
        //把音频设置为非加载完自动播放（部分web平台不允许未交互就有音频播放）
        this.bgmSource.playOnAwake = true;
    }

    public get AudioSource(): AudioSource {
        return this.bgmSource;
    }

    /**
     * 播放背景音乐
     * @param sound 音频剪辑或者resources的音频路径
     * @param volume 
     */
    playBgm(clip: AudioClip | string, volume: number = this._volume) {
        if (!this._sound_on) {
            this._volume = 0;
        } else {
            this._volume = volume;
        }
        let sound = clip;
        if (!sound) {
            console.error("背景音乐为空");
            return;
        }
        if (sound instanceof AudioClip) {
            this.bgmSource.stop();
            this.bgmSource.clip = sound; //考虑到切换背景音乐时，先停止后播放，防止出现播放叠加或不播放的问题
            this.bgmSource.play();
            this.bgmSource.loop = true;
            this.bgmSource.volume = this._volume;
        } else {
            console.error("背景音乐加载失败", sound);
        }
    };

    /**
     * 播放音效1 预加载方式
     * @param soundtype 音频类型（定义）
     * @param volume 
     */
    playEffect(clip: AudioClip, volume: number = this._volume) {

        if (!clip || !this.effectSource) return;

        // 创建临时节点避免打断正在播放的音效:cite[2]
        const effectNode = new Node();
        const audioSource = effectNode.addComponent(AudioSource)!;

        audioSource.clip = clip;
        audioSource.volume = volume;
        audioSource.play(); // 播放一次自动销毁

        // 播放完成后销毁节点
        setTimeout(() => effectNode.destroy(), clip.getDuration() * 1000 + 100);
    }


    playClickEffect() {
        this.playEffectWithName('dianji')
    }

    playEffectWithName(name) {
        resources.load(`sounds/${name}`, (error, clip: AudioClip) => {
            this.playEffect(clip)
        })
    }

    /**
     * 客户端音效开关
     * @param soundOpen 
     */
    setMenu(soundOpen: boolean) {
        this._sound_on = soundOpen;
        if (!this._sound_on) {
            this.bgmSource.volume = 0;
            this.effectSource.volume = 0;
            this._volume = 0;
        } else {
            this.bgmSource.volume = 1.0;
            this.effectSource.volume = 1.0;
            this._volume = 1.0;
        }
    }
    /**
     * 停止背景音乐
     */
    stopBgm() {
        this.bgmSource.stop();
    }

    /**
     * 暂停背景音乐
     */
    pauseBgm() {
        this.bgmSource.pause();
    }
    /**
     * 恢复背景音乐
     */
    resumeBgm() {
        this.bgmSource.play();
    }
}


